//
//  TTHTTPServer.swift
//  TTCOM
//
//  Created by Toj on 3/11/21.
//

import Foundation
import HandyJSON

open class TTHTTPServer: NSObject {
    
    public static let shared = TTHTTPServer()
    private lazy var service: TTNetworkProtocol? = AFNService.shared
    
    // private lazy var service: TTNetworkService = AFService.shared
    
    public func request<T: TTJSONCodable>(api: String,
                                   model:T.Type,
                                   type: TTHTTPRequestType = .post,
                                   hearders:[String : String]? = nil,
                                   parameters:[String: Any]? = nil,
                                   prepare execute:(()->())? = nil,
                                   completion: ((_ t:TTResponse<T>)->())?) {
        
        service?.request(url: api, request: type, headers: hearders, parameters: parameters)
        { (response) in
            
            if let json = response as? Dictionary<String, Any> {
                
                // let rModel = TTResponse<T>.tt_model(json:json)
                // let rModel = json.kj.model(TTResponse<T>.self)
                if let rModel = TTResponse<T>.deserialize(from: json) {
                    completion?(rModel)
                    return
                }
            }
            
            let rModel = TTResponse<T>()
            rModel.message = "数据异常, 请联系官方人员"
            completion?(rModel)
        } failure: { (error) in
            
            let aError = error as NSError
            let rModel:TTResponse<T> = TTResponse<T>.init()
            rModel.code = .timeout
            rModel.message = aError.domain
            completion?(rModel)
        }
    }
}
